package com.example.db;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.db.bean.User;
import com.example.db.utils.KryoUtil;
import com.example.db.utils.TimeUtils;

import junit.framework.TestCase;

import org.junit.Test;

/**
 * Created by kkmike999 on 16/2/12.
 */
public class SharedPreTest extends TestCase {

	public static final int    COUNT  = 10000;
	public static final String dbName = "shared" + (int) (Math.random() * 100);

	private SharedPreferences        sharedPreferences;
	private SharedPreferences.Editor editor;

	private User[] users = UserHelper.createUserList(COUNT);

	@Override
	public void setUp() throws Exception {
		sharedPreferences = DbApp.getContext().getSharedPreferences(dbName, Context.MODE_PRIVATE);
		editor = sharedPreferences.edit();
	}

	@Override
	public void tearDown() throws Exception {
		editor.clear();
		editor.commit();
	}

	@Test
	public void sharedPrePutInt() {
		TimeUtils.begin();

		for (User user : users) {
			editor.putInt(user.name, user.uid);
		}
		editor.commit();

		System.out.println("SharedPreTest(" + users.length + ") : put int time = " + TimeUtils.time());
	}

	@Test
	public void sharedPrePutEveryCommit() {
		TimeUtils.begin();

		User[] users = new User[100];

		for (int i = 0; i < 100; i++) {
			users[i] = this.users[i];
		}

		for (User user : users) {
			editor.putInt(user.name, user.uid);
			editor.commit();
		}

		System.out.println("SharedPreTest(" + users.length + ") : put int every commit , time = " + TimeUtils.time());
	}

	@Test
	public void sharedPrePutObj() {

		TimeUtils.begin();

		for (User user : users) {
			if (sharedPreferences.contains(user.name)) { // 几乎不耗时
				continue;
			}

			String string = KryoUtil.toString(user);

			editor.putString(user.name, string);
		}
		editor.commit();

		System.out.println("SharedPreTest(" + users.length + ") : put Obj time = " + TimeUtils.time());
	}

	@Test
	public void sharedPreDelObj() {
		sharedPrePutObj();

		TimeUtils.begin();

		for (User user : users) {
			editor.remove(user.name);
		}
		editor.commit();

		System.out.println("SharedPreTest(" + users.length + ") : del Obj time = " + TimeUtils.time());
	}

	@Test
	public void sharedGetObj() {
		sharedPrePutObj();

		TimeUtils.begin();

		for (User user : users) {
			String string = sharedPreferences.getString(user.name, "");
			User u = KryoUtil.parseString(string, User.class);
		}

		System.out.println("SharedPreTest(" + users.length + ") : get Obj time = " + TimeUtils.time());
	}
}
